#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        cout << "./udpclient" << "[ip]" << " [port]" << endl;
    }
    string ip = argv[1];
    uint16_t port = stoi(argv[2]);

    // 创建socket
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cout << "client create fail" << endl;
    }
    //客户端不需要bind，但是客户端会在发送数据时有OS随机bind一个端口，因为客户端设备同时请求多个服务端，服务端很难让客户端的程序为其留一个固定的端口，而且没必要第一时间直到客户端的端口，客户端发送数据请求时可以获取到

    // 创建服务端信息的结构体
    struct sockaddr_in server;
    server.sin_port = htons(port);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    socklen_t len = sizeof(server);

    char buf[1024] = {0};
    string message;
    while (1)
    {
        // 发送数据
        cout << "Please Enter@";
        getline(cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, len);

        // 接收数据
        struct sockaddr_in tem;
        socklen_t len_tem = sizeof(tem);
        ssize_t n = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&tem, &len);
        if (n < 0)
        {
            cout << "client receive fail" << endl;
            continue;
        }
        buf[n] = 0;
        cout << buf << endl;
    }
}